package webHandle

import (
	"fmt"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
	"github.com/valyala/fasthttp"
	"log"
	"net/http"
)

func WXLoginGet(c *gin.Context) {
	jsCode := c.Query("code")
	if len(jsCode) <= 0 {
		log.Fatal("invalid params of code")
	}
	var (
		appId     = "wx4cb8122b41c8dd5f"
		appSecret = "e5584d8d1b351fb0fbd9bafe3a334176"
		result    struct {
			OpenId     string `json:"openid"`
			SessionKey string `json:"session_key"`
			UnionId    string `json:"unionid"`
			ErrCode    int    `json:"errcode"`
			ErrMsg     string `json:"errmsg"`
		}
	)

	url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	statusCode, body, err := fasthttp.Get(nil, fmt.Sprintf(url, appId, appSecret, jsCode))
	if err != nil {
		log.Fatal(err)
	} else if statusCode != fasthttp.StatusOK {

	} else if err = jsoniter.Unmarshal(body, &result); err != nil {
		log.Fatal(err)
	}

	c.JSON(http.StatusOK, gin.H{
		"open_id":     result.OpenId,
		"session_key": result.SessionKey,
		"union_id":    result.UnionId,
	})
}
